package com.topc.problem.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.topc.problem.mapper.ProblemTagMidMapper;
import com.topc.problem.model.po.ProblemTagMid;
import com.topc.problem.service.IProblemTagMidService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProblemTagMidServiceImpl extends ServiceImpl<ProblemTagMidMapper, ProblemTagMid> implements IProblemTagMidService{


    @Override
    public List<Long> searchTagsToProblemIdPrecise(int pageSize,int pageIndex,List<Long> tagIds) {
        LambdaQueryWrapper<ProblemTagMid> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(ProblemTagMid::getProblemId)
                .in(ProblemTagMid::getTagId,tagIds).groupBy(ProblemTagMid::getProblemId)
                .last("order by count(*) desc limit "+pageSize*(pageIndex-1)+","+pageSize);
        return getBaseMapper().selectList(lambdaQueryWrapper).stream().map(ProblemTagMid::getProblemId).collect(Collectors.toList());
    }

    @Override
    public List<Long> searchTagsToProblemIdNotPrecise(int pageSize, int pageIndex, List<Long> tagIds) {
        LambdaQueryWrapper<ProblemTagMid> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(ProblemTagMid::getProblemId)
                .in(ProblemTagMid::getTagId,tagIds).groupBy(ProblemTagMid::getProblemId)
                .last("having count(*) = "+tagIds.size()+" limit "+pageSize*(pageIndex-1)+","+pageSize);
        return getBaseMapper().selectList(lambdaQueryWrapper).stream().map(ProblemTagMid::getProblemId).collect(Collectors.toList());

    }

    @Override
    public List<Long> getProblemAllTags(Long problemId) {
        LambdaQueryWrapper<ProblemTagMid> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(ProblemTagMid::getTagId).eq(ProblemTagMid::getProblemId,problemId);
        return getBaseMapper().selectList(lambdaQueryWrapper).stream().map(ProblemTagMid::getTagId).collect(Collectors.toList());
    }

    @Override
    public void updateProblemTag(Long problemId, List<Long> tags) {
        LambdaUpdateWrapper<ProblemTagMid> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ProblemTagMid::getProblemId,problemId);
        this.remove(updateWrapper);
        List<ProblemTagMid> collect = tags.stream().map(tag ->{
            return new ProblemTagMid(problemId,tag);
        }).collect(Collectors.toList());
        this.saveBatch(collect);
    }

}
